package imclient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.qiyu.live.im.constants.ImMsgCodeEnum;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.core.server.common.TcpImMsgDecoder;
import org.qiyu.live.im.core.server.common.TcpImMsgEncoder;

import java.io.IOException;

public class SmClientApplication {


    private void startConnection(String address, int port) throws IOException, InterruptedException {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                System.out.println("初始化链接建立");
                socketChannel.pipeline().addLast(new TcpImMsgEncoder());
                socketChannel.pipeline().addLast(new TcpImMsgDecoder());
                socketChannel.pipeline().addLast(new ClientHandler());
            }
        });


        ChannelFuture connect = bootstrap.connect(address, port).sync();
        Channel channel = connect.channel();
        while(true){

            if (channel.isActive()) {

                channel.writeAndFlush(ImMsg.build(ImMsgCodeEnum.IM_BIZ_MSG.getCode(), "{\"appId\":30000,\"bizCode\":0,\"data\":\"666\",\"msgId\":\"1233333\",\"token\":\"234354362435\",\"userId\":120000}"));
                System.out.println("打印成功");
                Thread.sleep(5000);

            }else {
                System.out.println("链接断开，请重试");
                if(connect.isSuccess()){
                    channel = connect.channel();
                }else {
                    System.err.println("连接失败，尝重连");
                    // 计算延迟时间（指数退避）
                    long delay = 10000 * (1L << 0);
                    // 安排下一次重连
                    connect.channel().eventLoop();
                    Thread.sleep(5000);

                }
            }

        }

    }


    public static void main(String[] args) throws IOException, InterruptedException {
        SmClientApplication imClientApplication = new SmClientApplication();
        imClientApplication.startConnection("127.0.0.1", 8989);
    }

}
